import FB from "./FB";

let g_MemKeyValue = {}
let g_CacheSaveKV = {}
let g_IsDelaySave = false


export default class fbStorage
{
    public static Get(key:string):string
    { 
        if(g_MemKeyValue[key]!=undefined) return g_MemKeyValue[key]
        var re:string = cc.sys.localStorage.getItem(fbStorage.ToStorageKey(key))
        if(!fbStorage.IsEmpty(re))
            g_MemKeyValue[key] = re
        else
            re = ""

        return re
    }

    //判断某个变量是否为空
    public static IsEmpty(v) { return v==undefined||v==""||v==null }

    public static Set(key:string,value:string)
    {
        if(!value) value = ""
        value = value+""
        g_MemKeyValue[key] = value

        if(g_IsDelaySave)//延迟保存
        { 
            g_CacheSaveKV[key] = value
        }
        else//即时保存
        { 
            cc.sys.localStorage.setItem(fbStorage.ToStorageKey(key),value)
        }
    }

    //当前是否开启了延迟存储，延迟存储状态所有保存的值将缓冲在内存
    //直到IsDelaySave值为false
    public static get IsDelaySave():boolean {return g_IsDelaySave}
    public static set IsDelaySave(v:boolean) {   
        g_IsDelaySave=v

        if(!g_IsDelaySave)
        {
            for(var k in g_CacheSaveKV)
            {
                try{ 
                    var vv = g_CacheSaveKV[k] 
                    cc.sys.localStorage.setItem(fbStorage.ToStorageKey(k),vv) 
                }catch(msg)
                {
                    cc.error(msg)
                }
            }
            
            g_CacheSaveKV = {}

            //自动恢复为异步存储状态
            fbStorage.IsSyncSave = false
        }
    }

    static ToStorageKey(key:string):string
    {
        if(!FB.InFB) return key
        return FBInstant.player.getID() + "_"+ key
    }


    //用于临时切换为同步存盘
    public static IsSyncSave = false
}

 
//cc.sys.localStorage.removeItem(key) 